package com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.utils.Preferences;
import com.kongzue.dialog.interfaces.OnDismissListener;
import com.kongzue.dialog.v3.TipDialog;
import com.kongzue.dialog.v3.WaitDialog;
import com.ninetaildemonfox.zdl.socialproject.base.BaseActivity;
import com.ninetaildemonfox.zdl.ninetaildemonfox.utils.AppManager;
import com.ninetaildemonfox.zdl.socialproject.R;
import com.ninetaildemonfox.zdl.socialproject.mvp.contract.AuthenticateLoginContract;
import com.ninetaildemonfox.zdl.socialproject.mvp.presenter.AuthenticateLoginPresenter;
import com.ninetaildemonfox.zdl.socialproject.utils.ToastUtil;
import com.ninetaildemonfox.zdl.socialproject.utils.VerificationTimer;
import com.orhanobut.logger.Logger;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author NineTailDemonFox
 * @date 2019/7/17 9:03
 * 功能描述： 1忘记密码  2 注册账号  3 wx 4QQ
 * 联系方式：1037438704@qq.com
 */
public class AuthenticateLoginActivity extends BaseActivity implements AuthenticateLoginContract {

    @BindView(R.id.edit_psd)
    EditText editPsd;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.text_user_protocol)
    TextView textUserProtocol;
    @BindView(R.id.edit_code)
    EditText editCode;
    private boolean aBoolean = false;
    private int count;
    @BindView(R.id.text_login)
    TextView textLogin;
    @BindView(R.id.text_center)
    TextView textCenter;
    @BindView(R.id.ll_register_view)
    LinearLayout llRegisterView;
    @BindView(R.id.ll_psd)
    LinearLayout llPsd;
    @BindView(R.id.iamge_eye)
    ImageView iamgeEye;
    @BindView(R.id.image_left_finish)
    ImageView imageLeftFinish;
    @BindView(R.id.text_verification)
    TextView textVerification;
    @BindView(R.id.view_gone)
    View viewGone;
    private VerificationTimer verificationTimer;
    private AuthenticateLoginPresenter authenticate;
    private String send_type, bind_id;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_authenticate_login;
    }

    @Override
    protected void onInitialization(Bundle bundle) {
        Bundle extras = getIntent().getExtras();
        authenticate = new AuthenticateLoginPresenter(this, me);
        count = extras.getInt("count");
        if (extras.getString("bind_id") != null) {
            bind_id = extras.getString("bind_id");
        }
        if (extras.getString("token") != null) {
            token = extras.getString("token");
        }

        imageLeftFinish.setVisibility(View.VISIBLE);
        // 1,忘记密码  2,注册 3 wx 4qq   5 修改密码  6修改实际号验证 7 绑定手机号
        if (count == 1) {
            send_type = "retrieve";
            textCenter.setText("找回密码");
            llRegisterView.setVisibility(View.GONE);
            textLogin.setText("确定");
        } else if (count == 2) {
            send_type = "register";
            llRegisterView.setVisibility(View.VISIBLE);
            textCenter.setText("注册");
        } else if (count == 5) {
            String phone = Preferences.getInstance().getString(this, "name", "phone");
            editPhone.setText(phone);
            editPhone.setFocusable(false);
            editPhone.setFocusableInTouchMode(false);
            send_type = "mod_pass";
            textCenter.setText("修改密码");
            llRegisterView.setVisibility(View.GONE);
            textLogin.setText("确定");
        } else if (count == 6) {
            String phone = Preferences.getInstance().getString(this, "name", "phone");
            editPhone.setText(phone);
            editPhone.setFocusable(false);
            editPhone.setFocusableInTouchMode(false);
            send_type = "mod_bind";
            textCenter.setText("验证身份");
            llRegisterView.setVisibility(View.GONE);
            llPsd.setVisibility(View.GONE);
            textLogin.setText("下一步");
        } else if (count == 7) {
            send_type = "re_bind";
            textCenter.setText("绑定手机号");
            llRegisterView.setVisibility(View.GONE);
            llPsd.setVisibility(View.GONE);
            textLogin.setText("立即绑定");
            viewGone.setVisibility(View.GONE);
        } else {
            viewGone.setVisibility(View.GONE);
            send_type = "re_bind";
            llRegisterView.setVisibility(View.GONE);
            llPsd.setVisibility(View.GONE);
            textCenter.setText("绑定手机号");
            textLogin.setText("立即绑定");
        }
        verificationTimer = new VerificationTimer(60000, 1000, textVerification, R.color.white, R.drawable.drawable_register_bg, R.color.text_black);
    }

    @OnClick({R.id.text_login, R.id.iamge_eye, R.id.image_left_finish, R.id.text_user_protocol, R.id.text_verification})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iamge_eye:
                if (aBoolean == false) {
                    aBoolean = true;
                    iamgeEye.setSelected(aBoolean);
                    //设置EditText的密码为可见的
                    editPsd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    aBoolean = false;
                    iamgeEye.setSelected(aBoolean);
                    //设置密码为隐藏的
                    editPsd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                editPsd.setSelection(editPsd.getText().length());
                break;
            case R.id.text_login:
                //注册或者找回密码
                if (count == 1) {
                    authenticate.getResetPassword(editPhone.getText().toString().trim()
                            , editCode.getText().toString().trim()
                            , editPsd.getText().toString().trim(), "1", this);
                } else if (count == 2) {
                    //注册成功
//                    boolean password = PwdCheckUtil.isPassword(editPhone.getText().toString().trim());
//                    if (password) {
//                        ToastUtil.show("请输入6-16位数字字母混合,不能全为数字,不能全为字母,首位不能为数字");
//                    } else {
//                        ToastUtil.show("你成功了");
//                    }
//                    boolean letterOrDigit = PwdCheckUtil.isLetterOrDigit(editPhone.getText().toString().trim());
//
//                    String regex = "^(?![A-Za-z0-9]+$)(?![a-z0-9\\\\W]+$)(?![A-Za-z\\\\W]+$)(?![A-Z0-9\\\\W]+$)[a-zA-Z0-9\\\\W]{8,12}$";
//                    boolean matches = editPhone.getText().toString().trim().matches(regex);
//                    ToastUtil.show(""+matches);
//                    if (letterOrDigit){
//                        ToastUtil.show("请输入6-16位数字字母混合,不能全为数字,不能全为字母,首位不能为数字");
//                    }else {
//                        ToastUtil.show("你成功了");
//                    }

//                    if (isPassword(editPhone.getText().toString().trim())){
//                        ToastUtil.show("请输入6-16位数字字母混合,不能全为数字,不能全为字母,首位不能为数字");
//                        return;
//                    }
                    authenticate.getRegister(editPhone.getText().toString().trim(),
                            editCode.getText().toString().trim(),
                            editPsd.getText().toString().trim());
                } else if (count == 5) {
                    //修改密码
                    authenticate.getResetPassword(editPhone.getText().toString().trim()
                            , editCode.getText().toString().trim()
                            , editPsd.getText().toString().trim(), "2", this);
                } else if (count == 6) {
                    //换绑手机号验证
                    authenticate.bindPhone1(token, editPhone.getText().toString().trim(), editCode.getText().toString().trim());
                } else if (count == 7) {
                    authenticate.bindPhone2(token, editPhone.getText().toString().trim(), editCode.getText().toString().trim());
                } else if (count == 3) {
                    authenticate.threeLoginBind(bind_id, editPhone.getText().toString().trim(), editCode.getText().toString().trim(), token);
                } else if (count == 4) {
                    authenticate.threeLoginBind(bind_id, editPhone.getText().toString().trim(), editCode.getText().toString().trim(), token);
                } else {
                    Toast.makeText(this, "数据出错", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.image_left_finish:
                //注册或者找回密码
                finish();
                break;
            case R.id.text_user_protocol:
                //用户协议
                authenticate.getAgreement();
                break;
            case R.id.text_verification:
                //获取验证码
                if (count == 5) {
                    authenticate.getSendVerity(editPhone.getText().toString().trim(), send_type, token);
                    return;
                }
                authenticate.getSendVerity(editPhone.getText().toString().trim(), send_type);
                break;
            default:
        }
    }

    public static void start(Context me, int count) {
        // 1,忘记密码  2,注册 3 wx 4qq   5 修改密码  6修改实际号验证  7绑定手机号
        Intent intent = new Intent(me, AuthenticateLoginActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("count", count);
        intent.putExtras(bundle);
        me.startActivity(intent);
    }

    public static void start(Context me, int count, String bind_id) {
        // 1,忘记密码  2,注册 3 wx 4qq   5 修改密码  6修改实际号验证  7绑定手机号
        Intent intent = new Intent(me, AuthenticateLoginActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("count", count);
        bundle.putString("bind_id", bind_id);
        intent.putExtras(bundle);
        me.startActivity(intent);
    }

    public static void start(Context me, String token, int count, String bind_id) {
        // 1,忘记密码  2,注册 3 wx 4qq   5 修改密码  6修改实际号验证  7绑定手机号
        Intent intent = new Intent(me, AuthenticateLoginActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("count", count);
        bundle.putString("token", token);
        bundle.putString("bind_id", bind_id);
        intent.putExtras(bundle);
        me.startActivity(intent);
    }

    @Override
    public void loginSuccess(Map<String, String> getData) {
        Preferences.getInstance().commit(me, "name", "phone", getData.get("account"));
        Preferences.getInstance().commit(me, "name", "psd", editPsd.getText().toString().trim());
        Preferences.getInstance().commit(me, "user", "token", getData.get("token"));
        Preferences.getInstance().commit(me, "user", "sex", getData.get("sex"));
        Preferences.getInstance().commit(me, "user", "vip", getData.get("vip"));
        //判断是否已经填写
        Preferences.getInstance().commit(me, "user", "nickname", getData.get("nickname"));
        //判断是否已经填写
        Preferences.getInstance().commit(me, "user", "invite_code", getData.get("invite_code"));
        //环信登录
        huanxin(getData);

        TipDialog.show(me, "登录成功", TipDialog.TYPE.SUCCESS).setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                // 性别 1男 2 女
                String string = Preferences.getInstance().getString(me, "user", "sex");
                Logger.d("=========登录界面获取的性别==========" + string);
                if (TextUtils.isEmpty(string) || string.equals("0")) {
                    startActivity(new Intent(me, SelectiveSexActivity.class));
                } else if (string.equals("1")) {
                    if (!TextUtils.isEmpty(getData.get("invite_code"))) {
                        AppManager.getInstance().killAllActivity();
                        startActivity(new Intent(me, MainActivity.class));
                        return;
                    }
                    startActivity(new Intent(me, WelcomeActivity.class));
                } else if (string.equals("2")) {
                    if (!TextUtils.isEmpty(getData.get("nickname"))) {
                        AppManager.getInstance().killAllActivity();
                        startActivity(new Intent(me, MainActivity.class));
                        return;
                    }
                    EditorialMaterialsActivity.start(me, 1);
                }
            }
        });
    }


    private void huanxin(Map<String, String> getData) {
        EMClient.getInstance().login(getData.get("id") + "m", "123456", new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                Log.d("huanxin", "登录聊天服务器成功！");
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                Log.d("huanxin", "登录聊天服务器失败！");
            }
        });
    }


    @Override
    public void verifySuccess(Map<String, String> sendVerifyBean) {
        if (sendVerifyBean == null) {
            return;
        }
        verificationTimer.start();
        ToastUtil.show(sendVerifyBean.get("message"));
    }

    @Override
    public void loginFailed(String msg) {
    }

    @Override
    public void showLoading() {
        WaitDialog.show(me, null);
    }

    @Override
    public void hideLoading() {
        WaitDialog.dismiss();
    }

    @Override
    public void bindPhone1() {
        //换绑手机号
        start(this, 7);
        finish();
    }

    @Override
    public void bindPhone2() {
        //换绑成功
        finish();
    }

}